package com.xiebishe.mylibrary.base;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;

import org.greenrobot.eventbus.EventBus;

import java.lang.ref.WeakReference;
import java.util.Iterator;
import java.util.LinkedList;

/**
 * Activity管理类
 */
public class MyActivityManager {

    private static LinkedList<WeakReference<Activity>> mActivityStack;

    private static MyActivityManager instance;
    private int visibleActicityCount;

    private MyActivityManager() {
    }

    /**
     * 单一实例
     */
    public static MyActivityManager getInstance() {
        if (instance == null) {
            synchronized (MyActivityManager.class) {
                if (instance == null) {
                    instance = new MyActivityManager();
                }
            }
        }
        return instance;
    }

    /**
     * 增加可见的activity  onStart()时调用
     */
    public void addVisibleActivity() {
        visibleActicityCount++;
        if (visibleActicityCount == 1) {
            //第一次到前台
            EventBus.getDefault().post(new AppEvent.AppAppear());
        }
    }

    /**
     * 移除可见的activity onStop()时调用
     */
    public void removeVisibleActivity() {
        visibleActicityCount--;
        if (visibleActicityCount == 0) {
            //执行应用切换到后台的逻辑
            EventBus.getDefault().post(new AppEvent.AppDisappear());
        }
    }

    /**
     * 添加Activity到堆栈
     */
    public void addActivity(Activity activity) {
        if (mActivityStack == null) {
            mActivityStack = new LinkedList<>();
        }
        mActivityStack.add(new WeakReference<>(activity));
    }

    /**
     * 获取当前Activity（堆栈中最后一个压入的）
     */
    public Activity getCurrentActivity() {
        checkWeakReference();
        while (mActivityStack != null && !mActivityStack.isEmpty()){
            Activity fragmentActivity = mActivityStack.getLast().get();
            if(fragmentActivity==null||fragmentActivity.isFinishing()){
                removeActivity(fragmentActivity);
                continue;
            }else{
                return fragmentActivity;
            }
        }
        return null;
    }

    public Activity getPreActivity() {
        checkWeakReference();
        if (mActivityStack != null && mActivityStack.size() >= 2) {
            return mActivityStack.get(mActivityStack.size() - 2).get();
        }
        return null;
    }

    /**
     * 结束当前Activity（堆栈中最后一个压入的）
     */
    public void finishActivity() {
        Activity activity = getCurrentActivity();
        if (activity != null) {
            finishActivity(activity);
        }

    }

    /**
     * 结束指定的Activity
     */
    public void finishActivity(Activity activity) {
        if (activity != null && mActivityStack != null) {
            // 使用迭代器进行安全删除
            for (Iterator<WeakReference<Activity>> it = mActivityStack.iterator(); it.hasNext(); ) {
                WeakReference<Activity> activityReference = it.next();
                Activity temp = activityReference.get();
                // 清理掉已经释放的activity
                if (temp == null) {
                    it.remove();
                    continue;
                }
                if (temp == activity) {
                    it.remove();
                }
            }
            activity.finish();
        }
    }


    /**
     * 结束指定的Activity
     */
    public void removeActivity(Activity activity) {
        if (activity != null && mActivityStack != null) {
            // 使用迭代器进行安全删除
            for (Iterator<WeakReference<Activity>> it = mActivityStack.iterator(); it.hasNext(); ) {
                WeakReference<Activity> activityReference = it.next();
                Activity temp = activityReference.get();

                // 清理掉已经释放的activity
                if (temp == null) {
                    it.remove();
                    continue;
                }
                if (temp == activity) {
                    it.remove();
                }
            }
        }
    }

    /**
     * 结束指定类名的Activity
     */
    public void finishActivity(Class<?> cls) {
        if (mActivityStack != null) {
            // 使用迭代器进行安全删除
            for (Iterator<WeakReference<Activity>> it = mActivityStack.iterator(); it.hasNext(); ) {
                WeakReference<Activity> activityReference = it.next();
                Activity activity = activityReference.get();
                // 清理掉已经释放的activity
                if (activity == null) {
                    it.remove();
                    continue;
                }
                if (activity.getClass().equals(cls)) {
                    it.remove();
                    activity.finish();
                }
            }
        }

    }

    /**
     * 结束所有Activity
     */
    public void finishAllActivity() {
        if (mActivityStack != null) {
            for (WeakReference<Activity> activityReference : mActivityStack) {
                Activity activity = activityReference.get();
                if (activity != null) {
                    activity.finish();
                }
            }
            mActivityStack.clear();
        }

    }

    /**
     * 退出应用程序
     */
    public void exitApp(Context context) {
        try {
            finishAllActivity();
            ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
            activityManager.restartPackage(context.getPackageName());
            System.exit(0);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 检查弱引用是否释放，若释放，则从栈中清理掉该元素
     */
    private void checkWeakReference() {
        if (mActivityStack != null) {
            // 使用迭代器进行安全删除
            for (Iterator<WeakReference<Activity>> it = mActivityStack.iterator(); it.hasNext(); ) {
                WeakReference<Activity> activityReference = it.next();
                Activity temp = activityReference.get();
                if (temp == null) {
                    it.remove();
                }
            }
        }
    }

}